package com.foxit.setting;

import java.io.*;
import java.net.*;
import java.lang.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Date;
import java.util.SimpleTimeZone;
import java.text.SimpleDateFormat;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.couchbase.client.CouchbaseClient;

public class SettingOnline extends HttpServlet {
   public void doGet(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
      response.setContentType("text/html;charset=UTF-8");
      request.setCharacterEncoding("UTF-8");
      PrintWriter outp = response.getWriter();
      outp.println("<HTML>");
      outp.println("<BODY>");
      String couch = request.getParameter("couch");
      String date = request.getParameter("date");
      if(couch==null || couch.length()==0) {
         outp.println("couch=? no couchbase hostname");
         outp.println("</BODY></HTML>");
         return;
      }
      if(date==null || date.length()==0) {
         outp.println("date=? no date(yyyy-MM-dd HH:mm:ss)");
         outp.println("</BODY></HTML>");
         return;
      }
      CouchbaseClient client=null;
      String key="", value="";
      try {
         List<URI> hosts = Arrays.asList(new URI("http://"+couch+":8091/pools"));
         client = new CouchbaseClient(hosts, "default", "");
         MongoClient mongo = new MongoClient("192.201.108.97", 27017);
         DB db = mongo.getDB("settingdb");
         DBCollection t_setlog = db.getCollection("setlog"); 
         DBCollection t_adid = db.getCollection("adid"); 
         DBCollection t_adrule = db.getCollection("adrule"); 
         DBCollection t_top = db.getCollection("top"); 
         DBCollection t_action = db.getCollection("action"); 
         DBCollection t_adana = db.getCollection("adana"); 
         DBCollection t_adanarule = db.getCollection("adanarule"); 
         DBCollection t_default = db.getCollection("default"); 
         DBCollection t_groupad = db.getCollection("groupad"); 
         DBCollection t_grouptype = db.getCollection("grouptype"); 
         DBCollection t_impmsgad = db.getCollection("impmsgad"); 
         DBCollection t_policy = db.getCollection("policy"); 
         DBCollection t_round = db.getCollection("round"); 
         DBCollection t_member = db.getCollection("member"); 
         DBCollection t_server = db.getCollection("server"); 
         BasicDBObject query = new BasicDBObject("start",date);
         int i=0;
         DBCursor cursor;
         List list = new ArrayList();
// TOP
         cursor = t_top.find(query);
         while (cursor.hasNext()) {
            HashMap map= new HashMap();
            Top s = (Top) JSON.parseObject(cursor.next().toString(),Top.class);
            map.put("server",s.getServer());
            map.put("group",s.getGroupname());
            map.put("age",s.getStatsday());
            map.put("count",s.getCount());
            list.add(map);
         }
         cursor.close();
         HashMap map1= new HashMap();
         map1.put("topkey",list);
         String json=JSON.toJSONString(map1, SerializerFeature.UseSingleQuotes);
         client.set("TOP",json).get();
//ADANA
         cursor = t_adana.find(query);
         list = new ArrayList();
         while (cursor.hasNext()) {
            HashMap map= new HashMap();
            Adana s = (Adana) JSON.parseObject(cursor.next().toString(),Adana.class);
            map.put("id",s.getId());
            map.put("group",s.getGrp());
            map.put("log",s.getLog());
            map.put("expr",s.getExpr());
            map.put("count",s.getCount());
            map.put("modify",s.getModify_unixtime());
            list.add(map);
         }
         cursor.close();
         map1 = new HashMap();
         map1.put("datagroup",list);
         json=JSON.toJSONString(map1, SerializerFeature.UseSingleQuotes);
         client.set("ADGROUP",json).get();
// ADANARULE
         cursor = t_adanarule.find(query);
         list = new ArrayList();
         while (cursor.hasNext()) {
            Adanarule s = (Adanarule) JSON.parseObject(cursor.next().toString(),Adanarule.class);
            HashMap map= new HashMap();
            map.put("rule",s.getRule());
            map.put("dimen",s.getDimen());
            map.put("group",s.getGrp());
            map.put("age",s.getStatsday());
            map.put("h",s.getHigh());
            map.put("m",s.getMedium());
            map.put("l",s.getLow());
            list.add(map);
         }
         cursor.close();
         map1= new HashMap();
         map1.put("datarule",list);
         json=JSON.toJSONString(map1, SerializerFeature.UseSingleQuotes);
         client.set("RULEGROUP",json).get();
// AD
         list=(List) t_adid.distinct("adrule");
         for(i=0;i < list.size();i++) {
            DBObject myDoc= t_adrule.findOne(new BasicDBObject("start",date).append("adrule",list.get(i).toString()));
            if(myDoc ==null) continue;
            Adrule r = (Adrule) JSON.parseObject(myDoc.toString(),Adrule.class);
            key = "AD_"+list.get(i).toString();
            value = r.getAdvertiser()+":"+r.getRelated();
            BasicDBObject query1 = new BasicDBObject("start",date).append("adrule",list.get(i).toString());
            cursor = t_adid.find(query1);
            while (cursor.hasNext()) {
               Adid s = (Adid) JSON.parseObject(cursor.next().toString(),Adid.class);
               value += ";"+s.getLang()+","+s.getAdid()+","+s.getAdimg()+","+s.getAdurl();
            }
            cursor.close();
            client.set(key,value).get(); 
         }
// MEMBER
         cursor = t_member.find(query);
         key="MEMBER";
         value="";
         i=0;
         while (cursor.hasNext()) {
            Member s = (Member) JSON.parseObject(cursor.next().toString(),Member.class);
            DBObject p = t_policy.findOne(new BasicDBObject("start",date).append("type",s.getType()));
            if(p != null) {
               Policy r = (Policy) JSON.parseObject(p.toString(),Policy.class); 
               if(i != 0) value += ";";
               else i++;
               value += s.getMember()+":"+s.getType()+":"+ r.getShow_time_every_hour()+":"+r.getShow_mode();
            }
         }
         cursor.close(); 
         client.set(key,value).get();
// SERVER
         list=(List) t_server.distinct("server");
         for(i =0;i < list.size();i++) {
            BasicDBObject query1 = new BasicDBObject("start",date).append("server",list.get(i));
            key="SERVER_"+list.get(i);
            value = "";
            cursor = t_server.find(query1); 
            int k=0;
            while (cursor.hasNext()) {
               Server s = (Server) JSON.parseObject(cursor.next().toString(),Server.class);
               if(k!=0)
                  value += ";";
               else
                  k++; 
               value += s.getShow_mode()+":"+s.getGroupno();
               for(int j=0;j < s.getGroupno();j++) {
                  DBObject p = t_grouptype.findOne(new BasicDBObject("start",date).append("server",s.getServer()).append("show_mode",s.getShow_mode()).append("groupno",j+1));
                  if(p != null) {
                     Grouptype r = (Grouptype) JSON.parseObject(p.toString(),Grouptype.class);
                     if(r.getType()==2) {
                        value += ":"+r.getType()+"!"+r.getAdrule();
                        String[] adl=r.getAdrule().split(",");
// MULTI ACTION
                        if(adl.length > 1) {
                           String akey="ACT_"+r.getAdrule();
                           String avalue="";
                           i=0;
                           for(String ad:adl) {
                              if(i > 0) avalue += ";";
                              else i++;
                              BasicDBObject query2 = new BasicDBObject("start",date).append("name",ad);
                              DBCursor cursor2 = t_action.find(query2);
                              while (cursor2.hasNext()) {
                                 Action x = (Action) JSON.parseObject(cursor2.next().toString(),Action.class);
                                 String H="", M="", L="", D="";
                                 DBObject myDoc= t_adanarule.findOne(new BasicDBObject("start",date).append("rule",x.getName()));
                                 if(myDoc != null) {
                                    Adanarule u = (Adanarule) JSON.parseObject(myDoc.toString(),Adanarule.class);
                                    D = u.getDimen();
                                    myDoc= t_adrule.findOne(new BasicDBObject("start",date).append("adrule",x.getHigh()));
                                    if(myDoc == null) {
                                       DBObject myDoc1= t_round.findOne(new BasicDBObject("start",date).append("name",x.getHigh()));
                                       if(myDoc1 != null) {
                                          Round rd = (Round) JSON.parseObject(myDoc1.toString(),Round.class);
                                          H = rd.getAdlist();
                                       }
                                    } else H=x.getHigh();
                                 }
                                 myDoc= t_adrule.findOne(new BasicDBObject("start",date).append("adrule",x.getMedium()));
                                 if(myDoc == null) {
                                    DBObject myDoc1= t_round.findOne(new BasicDBObject("start",date).append("name",x.getMedium()));
                                    if(myDoc1 != null) {
                                       Round rd = (Round) JSON.parseObject(myDoc1.toString(),Round.class);
                                       M = rd.getAdlist();
                                    }
                                 } else M=x.getMedium();
                                 myDoc= t_adrule.findOne(new BasicDBObject("start",date).append("adrule",x.getLow()));
                                 if(myDoc == null) {
                                    DBObject myDoc1= t_round.findOne(new BasicDBObject("start",date).append("name",x.getLow()));
                                    if(myDoc1 != null) {
                                       Round rd = (Round) JSON.parseObject(myDoc1.toString(),Round.class);
                                       L = rd.getAdlist();
                                    }
                                 } else L=x.getLow();
                                 avalue += x.getName()+":"+D+":"+x.getMotion()+":"+H+":"+M+":"+L;
                              }
                              cursor2.close();
                           }
                           client.set(akey,avalue).get();
                        }
                     } else {
                        DBObject myDoc= t_adrule.findOne(new BasicDBObject("start",date).append("adrule",r.getAdrule()));
                        if(myDoc != null) {
                           value += ":"+r.getType()+"!"+r.getAdrule();
                        } else {
                           myDoc= t_round.findOne(new BasicDBObject("start",date).append("name",r.getAdrule()));
                           if(myDoc!=null) {
                              Round o = (Round) JSON.parseObject(myDoc.toString(),Round.class);
                              value += ":"+r.getType()+"!"+o.getAdlist();
                           }
                        }
                     }
                  }
               }
            }
            cursor.close();
            client.set(key,value).get();
         }
// LANGS
         list=(List) t_adid.distinct("lang");
         if(list.size() > 0) {
            key = "LANGS";
            value = "";
            for(i=0;i < list.size();i++) {
               if(i==0) {
                  value += list.get(i).toString();
               } else {
                  value += ","+list.get(i).toString();
               }
            }
            client.set(key,value).get();
         } 
// ADVERTISER
         list=(List) t_adrule.distinct("advertiser");
         if(list.size() > 0) {
            key = "ADVERTISER";
            value = "";
            for(i=0;i < list.size();i++) {
               if(i==0) {
                  value += list.get(i).toString();
               } else {
                  value += ","+list.get(i).toString();
               }
            } 
            client.set(key,value).get();
         }
// REL
         list=(List) t_adrule.distinct("related");
         for(i=0;i < list.size();i++) {
            key = "REL_"+list.get(i).toString();
            value = "";
            BasicDBObject query1 = new BasicDBObject("start",date).append("related",list.get(i));
            cursor = t_adrule.find(query1); 
            int k=0;
            while (cursor.hasNext()) {
               Adrule s = (Adrule) JSON.parseObject(cursor.next().toString(),Adrule.class);
               if(k!=0) value += ",";
               else k++;
               value += s.getAdrule();
            }
            cursor.close();
            client.set(key,value).get();
         }
//DIMENSION
         list=(List) t_adanarule.distinct("dimen");
         if(list.size() > 0) {
            key = "DIMENSION";
            value = "";
            for(i=0;i < list.size();i++) {
               if(i==0) {
                  value += list.get(i).toString();
               } else {
                  value += ","+list.get(i).toString();
               }
            } 
            client.set(key,value).get();
         }
// DEFAULTAD
         cursor = t_default.find(query);
         key = "DEFAULTAD";
         value = "";
         i = 0;
         while (cursor.hasNext()) {
            Default s = (Default) JSON.parseObject(cursor.next().toString(),Default.class);
            if(i!=0) value += ",";
            else i++;
            value += s.getAdlist();
         }
         cursor.close();
         client.set(key,value).get();
// IMPMSG
         cursor = t_impmsgad.find(query);
         key = "IMPMSG";
         value = "";
         i = 0;
         while (cursor.hasNext()) {
            Impmsgad s = (Impmsgad) JSON.parseObject(cursor.next().toString(),Impmsgad.class);
            if(i!=0) value += ",";
            else i++;
            value += s.getAdlist();
         }
         cursor.close();
         client.set(key,value).get();
// ACTION 
         cursor = t_action.find(query);
         while (cursor.hasNext()) {
            Action s = (Action) JSON.parseObject(cursor.next().toString(),Action.class);
            key = "ACT_"+s.getName();
            value = "";
            String H="", M="", L="", D="";
            DBObject myDoc= t_adanarule.findOne(new BasicDBObject("start",date).append("rule",s.getName()));
            if(myDoc != null) {
               Adanarule u = (Adanarule) JSON.parseObject(myDoc.toString(),Adanarule.class);
               D = u.getDimen(); 
               myDoc= t_adrule.findOne(new BasicDBObject("start",date).append("adrule",s.getHigh()));
               if(myDoc == null) {
                   DBObject myDoc1= t_round.findOne(new BasicDBObject("start",date).append("name",s.getHigh()));
                   if(myDoc1 != null) {
                      Round r = (Round) JSON.parseObject(myDoc1.toString(),Round.class);
                      H = r.getAdlist(); 
                   }
               } else H=s.getHigh();
               myDoc= t_adrule.findOne(new BasicDBObject("start",date).append("adrule",s.getMedium()));
               if(myDoc == null) {
                   DBObject myDoc1= t_round.findOne(new BasicDBObject("start",date).append("name",s.getMedium()));
                   if(myDoc1 != null) {
                      Round r = (Round) JSON.parseObject(myDoc1.toString(),Round.class);
                      M = r.getAdlist(); 
                   }
               } else M=s.getMedium();
               myDoc= t_adrule.findOne(new BasicDBObject("start",date).append("adrule",s.getLow()));
               if(myDoc == null) {
                   DBObject myDoc1= t_round.findOne(new BasicDBObject("start",date).append("name",s.getLow()));
                   if(myDoc1 != null) {
                      Round r = (Round) JSON.parseObject(myDoc1.toString(),Round.class);
                      L = r.getAdlist(); 
                   }
               } else L=s.getLow();
               value += s.getName()+":"+D+":"+s.getMotion()+":"+H+":"+M+":"+L;
               client.set(key,value).get();
            }
         }
         cursor.close(); 
// GROUP
         key = "GROUP";
         value = "";
         cursor = t_groupad.find(query);
         i =0;
         while (cursor.hasNext()) {
            Groupad s = (Groupad) JSON.parseObject(cursor.next().toString(),Groupad.class);
            DBObject myDoc= t_adanarule.findOne(new BasicDBObject("start",date).append("rule",s.getName()));
            if(myDoc != null) {
               Adanarule u = (Adanarule) JSON.parseObject(myDoc.toString(),Adanarule.class);
               if(i != 0) value += ":";
               else i++;
               value += s.getName()+","+u.getDimen()+","+s.getHigh()+","+s.getMedium()+","+s.getLow();
            }
         } 
         cursor.close(); 
         client.set(key,value).get();
         client.shutdown();
         BasicDBObject doc = new BasicDBObject("$set",
                        new BasicDBObject().append("online",0));
         t_setlog.update(new BasicDBObject().append("online",1), doc);
         Date now = new Date();
         doc = new BasicDBObject("$set",
                     new BasicDBObject().append("modify_time",now)
                     .append("online",1));
         t_setlog.update(new BasicDBObject().append("start",date), doc); 
      } catch(Exception ex) {
          outp.println("mongodb exception:"+ex.getMessage());
      } 
      outp.println("ok, done");
      outp.println("</HTML>");
      outp.println("</BODY>");
   }
}
